/**
 * Created by XianTao on 2016/11/27
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.base.api;

import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.util.ApiResult;
import org.lego.util.DateTimeUtil;
import org.lego.util.HttpUtil;
import org.lego.wechat.base.entity.WxJsTicket;
import org.lego.wechat.base.service.WxCorpService;
import org.lego.wechat.base.service.WxJsTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * jsapi_ticket是公众号用于调用微信JS接口的临时票据
 * 有效期为7200秒
 */
@Component
public class JsApiTicketApi {
    private String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    private String qyUrl = "";

    @Autowired
    private WxJsTicketService wxJsTicketService;
    @Autowired
    private WxCorpService wxCorpService;
    @Autowired
    private AccessTokenApi accessTokenApi;

    /**
     * 获取微信号corpId的jsTicket
     *
     * @param corpId  企业号corpId
     * @param agentId 应用ID
     * @return 微信号的jsTicket
     */
    public WxJsTicket getWxJsTicket(String corpId, Integer agentId) {
        WxJsTicket jsTicket = wxJsTicketService.findOneByCorpIdAndAgentId(corpId, agentId);
        if (!ObjectUtils.isEmpty(jsTicket)) {
            if (!ObjectUtils.isEmpty(jsTicket) && !ObjectUtils.isEmpty(jsTicket.getExpiredTime())
                    && jsTicket.getExpiredTime() > DateTimeUtil.getCurrentTimeSeconds()) {
                return jsTicket;
            }
        }
        return refreshJsTicket(corpId, agentId, wxCorpService.findOneByCorpIdAndAgentId(corpId, agentId).getCorpSecret(), jsTicket);
    }

    /**
     * 刷新jsTicket，并保存及其有效期
     *
     * @param corpId     corpId
     * @param agentId    应用ID
     * @param corpSecret 密钥
     * @param jsTicket   WxJsTicket
     * @return 微信号的jsTicket
     */
    private synchronized WxJsTicket refreshJsTicket(String corpId, Integer agentId, String corpSecret, WxJsTicket jsTicket) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", accessTokenApi.getWxAccessToken(corpId, agentId, corpSecret).getAccessToken());
        params.put("type", "jsapi");
        ApiResult apiResult = ApiResult.create(HttpUtil.get(url, params));
        if (!apiResult.isSucceed()) {
            throw new ExtraInvalidParameterException("WechatSystem.api.errorCode", String.valueOf(apiResult.getErrorCode()));
        }
        String ticket = apiResult.getStr("ticket");
        if (ObjectUtils.isEmpty(jsTicket)) {
            jsTicket = new WxJsTicket();
            jsTicket.setCorpId(corpId);
            jsTicket.setAgentId(agentId);
        }
        jsTicket.setTicket(ticket);
        // -120表示将过期时间提前2分钟 (微信服务器对过期的token，5分钟内仍有效)
        jsTicket.setExpiredTime(DateTimeUtil.getCurrentTimeSeconds() + (apiResult.getInt("expires_in") - 120));
        wxJsTicketService.saveAndFlush(jsTicket);
        return jsTicket;
    }
}
